#![allow(non_snake_case)]
use leptos::prelude::*;
use shq_web_controls::{TreeItems, TreeSelect};

// 导入服务器函数
use crate::utils::server_functions::{fetch_top_user};

#[component]
pub fn UserComponent(
    #[prop(optional, into)]
    sel_user_id: RwSignal<Option<u32>>,
) -> impl IntoView {
    // 获取员工数据
    let user_items = Resource::new(
        move || (),
        |_| async { fetch_top_user().await }
    );
    // 用户选择变更处理 - 只处理有效的用户ID
    let on_change = move |selected_key: Option<String>| {
        if let Some(key) = selected_key {
            if !key.starts_with("o_") {
                // 只处理不以"o_"开头的key
                if let Ok(id) = key.parse::<u32>() {
                    sel_user_id.set(Some(id));
                } else {
                    sel_user_id.set(None);
                }
            }
        } else {
            // 没有选择值时清空选择
            sel_user_id.set(None);
        }
    };
    view! {
        <div class="bg-white shadow rounded-lg p-4 flex-1 flex flex-col min-h-1">
            <h1 class="text-xl font-bold mb-4">用户</h1>
            <Suspense fallback=|| view! { <progress class="progress w-56"></progress> }>
                {move || match user_items.get() {
                    Some(Ok(user)) => {
                        let user_tree_items = StoredValue::new(TreeItems::from(&user));
                        let value = sel_user_id.with_untracked(|v|{
                            v.map(|id| id.to_string())
                        });
                        view! {
                            <div class="flex-1 overflow-y-auto min-h-1">
                                <TreeSelect
                                    // value=Some("79".to_string())
                                    value = value
                                    is_dropdown = false
                                    tree_items=user_tree_items
                                    on_change = on_change
                                />
                            </div>
                        }.into_any()
                    }
                    Some(Err(e)) => {
                        let error_message = e.to_string();
                        view! {
                            <div class="p-4 text-red-500">
                                {error_message}
                            </div>
                        }.into_any()
                    }
                    None => {
                        view! {
                            <div class="flex-1 flex items-center justify-center">
                                "正在加载数据..."
                            </div>
                        }.into_any()
                    }
                }}
            </Suspense>
        </div>
    }.into_any()
}